package com.tksflysun.im.common.util;

import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tksflysun.im.common.constants.Constants;

public class AESCBCUtil {
    private static final Logger logger = LoggerFactory.getLogger(AESCBCUtil.class);

    private static final String KEY_ALGORITHM = "AES";

    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

    static {
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        } else {
            Security.removeProvider("BC");
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        }
    }

    /**
     * 
     * @param content
     * @param key
     * @param ivStr
     * @return
     */
    public static byte[] encrypt(byte[] content, byte[] key, byte[] ivStr) {

        SecretKeySpec skeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(ivStr);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            return cipher.doFinal(content);

        } catch (Exception e) {
            logger.error("AES encryption operation has exception,content:{},password:{}", content, key, e);
        }
        return null;
    }

    /**
     * 
     * @param content
     * @param key
     * @param ivStr
     * @return
     */
    public static String encryptBase64(byte[] content, byte[] key, byte[] ivStr) {

        SecretKeySpec skeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM, "BC");
            IvParameterSpec iv = new IvParameterSpec(ivStr);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encryptedData = cipher.doFinal(content);
            return Base64.encodeBase64String(encryptedData);

        } catch (Exception e) {
            logger.error("AES encryption operation has exception,content:{},password:{}", content, key, e);
        }
        return null;
    }

    /**
     * 
     * @param content
     * @param key
     * @param ivStr
     * @return
     */
    public static String decrypt(byte[] content, byte[] key, byte[] ivStr) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM, "BC");
            IvParameterSpec iv = new IvParameterSpec(ivStr);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] original = cipher.doFinal(content);
            return new String(original);
        } catch (Exception e) {
            logger.error("AES decryption operation has exception,content:{},password:{}", content, key, e);
        }
        return null;
    }

    /**
     * AES 加密操作
     *
     * @param content
     *            待加密内容
     * @param password
     *            加密密码
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String password) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
            byte[] byteContent = content.getBytes(Charset.forName("UTF-8"));
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(byteContent);// 加密
            return Base64.encodeBase64String(result);// 通过Base64转码返回
        } catch (Exception ex) {
            logger.error("加密失败！", ex);
        }

        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param password
     * @return
     */
    public static String decrypt(String content, String password) {
        try {
            // 实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            // 使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
            // 执行操作
            byte[] result = cipher.doFinal(Base64.decodeBase64(content));
            return new String(result, "utf-8");
        } catch (Exception ex) {
            logger.error("解密失败！", ex);
        }

        return null;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String password) {
        // 返回生成指定算法密钥生成器的 KeyGenerator 对象
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            // AES 要求密钥长度为 128
            kg.init(128, new SecureRandom(password.getBytes(Charset.forName("UTF-8"))));
            // 生成一个密钥
            SecretKey secretKey = kg.generateKey();
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
        } catch (NoSuchAlgorithmException ex) {
            logger.error("生成加密密钥失败！", ex);
        }

        return null;
    }

    public static void main(String[] args) throws Exception {

        String mchId = "1550443051";
        String mchIdSalt = Md5Util.getMd5Str(mchId).toLowerCase().substring(16);
        String mchKey = "zhifeijishutksflysun123456789012";
        String mchKeySalt = Md5Util.getMd5Str(mchKey).toLowerCase().substring(16);

        System.out.println("mchIdSalt: " + mchIdSalt);
        System.out.println("mchKeySalt: " + mchKeySalt);

        String encryptMchId = AESCBCUtil.encryptBase64(mchId.getBytes(Charset.forName("UTF-8")),
            mchIdSalt.getBytes(Charset.forName("UTF-8")),
            Constants.USER_INFO_IV_KEY.getBytes(Charset.forName("UTF-8")));
        String encryptMchKey = AESCBCUtil.encryptBase64(mchKey.getBytes(Charset.forName("UTF-8")),
            mchKeySalt.getBytes(Charset.forName("UTF-8")),
            Constants.USER_INFO_IV_KEY.getBytes(Charset.forName("UTF-8")));
        System.out.println("encryptMchId: " + encryptMchId);
        System.out.println("encryptMchKey: " + encryptMchKey);

        String decryptMchId =
            AESCBCUtil.decrypt(Base64.decodeBase64(encryptMchId), mchIdSalt.getBytes(Charset.forName("UTF-8")),
                Constants.USER_INFO_IV_KEY.getBytes(Charset.forName("UTF-8")));

        String decryptMchKey =
            AESCBCUtil.decrypt(Base64.decodeBase64(encryptMchKey), mchKeySalt.getBytes(Charset.forName("UTF-8")),
                Constants.USER_INFO_IV_KEY.getBytes(Charset.forName("UTF-8")));

        System.out.println(mchId.equals(decryptMchId));
        System.out.println(mchKey.equals(decryptMchKey));
    }

}
